package com.google.android.apps.authenticator;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator2.R;

public class ChangeApplicationPasswordActivity extends Activity {

  private int errorCounter;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.change_application_password);
  }

  @Override
  protected void onStart() {
    super.onStart();
    errorCounter=1;
  }

  public void savePassword(View view){
    EditText editField1=(EditText) findViewById(R.id.databaseCurrentPassword);
    EditText editField2=(EditText) findViewById(R.id.databaseNewPassword);
    EditText editField3=(EditText) findViewById(R.id.databasePasswordConfirmation);
    String currentPassword=editField1.getText().toString();
    String newPassword=editField2.getText().toString();
    String passwordConfirmation=editField3.getText().toString();
    
    AccountDb mAccountDb = DependencyInjector.getAccountDb();
    if (!(newPassword.equals("") && passwordConfirmation.equals("")))
    {
      if (newPassword.equals(passwordConfirmation)) {
        if (newPassword.length()<AuthenticatorActivity.PASSWORD_MIN_LENGTH) {
          
          Toast.makeText(this, String.format(getResources().getString(R.string.wrong_password_size_label),AuthenticatorActivity.PASSWORD_MIN_LENGTH), Toast.LENGTH_LONG)
          .show();
        }
        else {
          if (mAccountDb.changePassword(currentPassword,newPassword))
            finish();
          else {
            new AlertDialog.Builder(this).setTitle(R.string.title_database_password_mismatch)
            .setMessage(R.string.database_current_password_mismatch)
            .setPositiveButton(R.string.ok, null).create().show();
            if (errorCounter++ > 2)
              finish();
          }
        }
      }
      else {
        new AlertDialog.Builder(this).setTitle(R.string.title_database_password_mismatch)
      .setMessage(R.string.database_password_mismatch)
      .setPositiveButton(R.string.ok, null).create().show();
      }
    }
  }
}
